package mm.yy.mybaties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * Created by Admin on 12/28 0028.
 */
public class MySessionFactory {
    private static final ThreadLocal<SqlSession> threadLocal=new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    private static String CONFIG_FILE_LOCATION="conf.xml";
    private static String configFile=CONFIG_FILE_LOCATION;
    static {
        try{
             //使用MyBatis提供的Resources类加载mybatis的配置文件
             Reader reader = Resources.getResourceAsReader(configFile);
             //构建sqlSession的工厂
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private static void builderSessionFactory(){
        //使用MyBatis提供的Resources类加载mybatis的配置文件
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(configFile);
            //构建sqlSession的工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession(){
        SqlSession sqlSession=threadLocal.get();
        if(sqlSession==null){
            if(sqlSessionFactory==null){
                builderSessionFactory();
            }
            sqlSession=(sqlSessionFactory!=null)?sqlSessionFactory.openSession(true):null;
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    public static void closeSession(){
        SqlSession sqlSession=threadLocal.get();
        threadLocal.set(sqlSession);
        if(sqlSession!=null){
            sqlSession.close();
        }
    }

}
